using System;

using Microsoft.SPOT;

using mfRCF.Core;
using mfRCF.Core.Extensions;

using mfXmlSerializer;

using mfLogger;

using OST.Shared;
using OST.Shared.SharedTypes;
using OST.Motor;
using OST.Anemometer;
using OST.Calc.Tracking;
using OST.Commands.Extensions;

namespace OST.Commands
{

    /// <summary>
    /// returns the next tracking-action <see cref="TrackingAction"/>
    /// </summary>
    public class TrackerNextActionGETCommand : mfRcfCommand
    {
        #region CTOR

        public TrackerNextActionGETCommand(string httpPath)
            : base(httpPath, new mfGETMethod())
        {
        }

        #endregion

        #region Properties

        /// <summary>
        /// wrapper-property 4 logging
        /// </summary>
        private ILoggerAppender Logger
        {
            get
            {
                return mfLogger.mfLogger.Instance;
            }
        }

        #endregion

        #region mfRcfCommand
        public override void ExecuteCommand(mfIHttpContext httpContext)
        {
            try
            {
                if (TrackerProvider.Instance == null
                    || TrackerProvider.Instance != null && !TrackerProvider.Instance.HasInstance)
                    throw new OSTException("no tracker instance found");

                if (!TrackerProvider.Instance.TrackerInstance.IsStarted)
                {   
                    this.WriteHttpResponseOK(httpContext, "tracker not started");
                }

                var actionSerializer = new mfXmlTypedSerializer(typeof(TrackingAction));

                httpContext.Response.ContentType = ContentTypeOut;
                httpContext.Response.StatusCode = enumHttpStatusCode.OK;

                //serialze(on) xml --> is too-memory-intensive, string copy seems to be more efficient
                //actionSerializer.SerializeOnStream(TrackerProvider.Instance.TrackerInstance.NextAction
                //                                    , httpContext.Response.OutputStream);
                var actionXmlString = actionSerializer.Serialize(TrackerProvider.Instance.TrackerInstance.NextAction);
                actionSerializer.Dispose();

                httpContext.Response.OutputStream.WriteString(actionXmlString);
                actionXmlString = null;
                httpContext.Response.Close();

                Logger.Debug(GetType() + " executed, " + Debug.GC(true) + " bytes free");
            }
            catch (Exception ex)
            {
                this.WriteHttpResponseError(httpContext, ex);
            }
        }

        #endregion
    }
}
